// 采用CURLOPT_WRITEFUNCTION 实现网页下载保存功能
#include <stdio.h>;
#include <stdlib.h>;
#include <unistd.h>;

#include <curl/curl.h>;
//#include <curl/types.h>;
#include <curl/easy.h>;

//这个函数是为了符合CURLOPT_WRITEFUNCTION而构造的
//完成数据保存功能
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    int written = fwrite(ptr, size, nmemb, (FILE *)stream);
    return written;
}

int post(FILE* fp) {

    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if (curl)
    {
        /*curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt"); // 指定cookie文件*/
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "logintype=uid&u=xieyan&psw=xxx86");    // 指定post内容
        //curl_easy_setopt(curl, CURLOPT_PROXY, "10.99.60.201:8080");
        curl_easy_setopt(curl, CURLOPT_URL, " http://mail.sina.com.cn/cgi-bin/login.cgi ");   // 指定url
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    fclose(fp);
    return true;
}

int main(int argc, char *argv[])
{
    FILE *fp;  //定义FILE类型指针
    CURL *curl;
    if (argc != 3)
    {
        fprintf(stderr, "usage: %s url filename\n", argv[0]);
        exit(-1);
    }


    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (NULL == curl) exit(-1);

    struct curl_slist *headers = NULL;
    /*headers = curl_slist_append(headers, "Content-Type: application/json");*/
    /*headers = curl_slist_append(headers, "Accept: application/json");// 改协议头*/
    /*curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);//设置HTTP头*/
    curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);//设置发送超时时间
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"&cmd=dlwz&game_id=56&area_id=0&group_id=1&mid=56&character_id=character_id&channel_id=channel_id&sub_channel_id=sub_channel_id&platform=1&deviceid=deviceid&itype=1");
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl,CURLOPT_VERBOSE,1);//打印调试信息
    /*[>curl_easy_setopt(curl, CURLOPT_HEADERDATA, fp); //将返回的html主体数据输出到fp指向的文件<]*/

    if((fp = fopen(argv[2],"w")) == NULL)
    {
        curl_easy_cleanup(curl);
        exit(1);
    }
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); //将返回的http头输出到fp指向的文件
    //CURLOPT_WRITEFUNCTION 将后继的动作交给write_data函数处理
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    CURLcode res = curl_easy_perform(curl);
    int info = 0;
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE  , &info);
    if (res != CURLE_OK || info != 200)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        exit(-1);
    }
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);

    /*post(fp);*/
    fclose(fp);

    return 0;
}
